# 用于上传文件到指定仓库软件库
# ps1 脚本里面非注释内容不要写中文，不然坑到死

param (
    [string]$file_path,
    [string]$artifact_server,
    [string]$artifact_owner,
    [string]$artifact_name,
    [string]$artifact_version,
    [string]$token_owner,
    [string]$token_value
)

if ($PSBoundParameters.Count -ne 7) {
    Write-Host "Parameter Error: Need 7 But Get $($PSBoundParameters.Count)"
    Write-Host "Parameter List: $($PSBoundParameters -join ', ')"
    exit 1
}

$ErrorActionPreference = "Stop"

if (-not (Test-Path $file_path)) {
    Write-Host "File Not exists"
    exit 1
}

$fileName = Split-Path $file_path -Leaf
$artifactUrl = "${artifact_server}/api/packages/${artifact_owner}/generic/${artifact_name}/${artifact_version}/$fileName"

try {
    # 拼接 token_owner 和 token_value
    $authPair = "${token_owner}:${token_value}"
    # 将拼接后的字符串转换为字节数组
    $authBytes = [System.Text.Encoding]::UTF8.GetBytes($authPair)
    # 将字节数组转换为 Base64 编码的字符串
    $base64Auth = [System.Convert]::ToBase64String($authBytes)
    # 构建最终的认证字符串
    $AuthStr = "Basic $base64Auth"
}
catch {
    # 处理异常并输出错误信息
    Write-Error "An error occurred: $_"
}

try {
    
    $response = Invoke-WebRequest -Uri $artifactUrl -Method 'GET' -UseBasicParsing -Headers @{"Authorization" = ${AuthStr} }
    $statusCode = $response.StatusCode
}
catch {
    $statusCode = $_.Exception.Response.StatusCode.Value__
}
if ($statusCode -eq 200) {
    Invoke-WebRequest -Uri $artifactUrl -Method Delete -UseBasicParsing -Headers @{"Authorization" = ${AuthStr} }
}
Invoke-WebRequest -Uri $artifactUrl -Method Put -InFile $file_path -UseBasicParsing -Headers @{"Authorization" = ${AuthStr} }